<template>
  <el-row>
    <el-card>
      <el-row>
        <el-col :span="10" style="font-size: 20px;line-height: 50px">
          {{ $t('productCenter.product.title') }}
        </el-col>
        <el-col :span="14" style="text-align: right">
          <el-button :loading="realtimeLoading" @click="realtimeUpdate">{{ $t('productCenter.product.liveUpdate') }}</el-button>
          <el-button @click="getRules">{{ $t('productCenter.product.editSettlementRules') }}</el-button>
          <el-button @click="add">{{ $t('productCenter.product.add') }}</el-button>
        </el-col>
      </el-row>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="inputData" :placeholder="$t('common.input')" class="input-with-select">
            <el-select slot="prepend" v-model="selectData">
              <el-option
                v-for="(item, index) in $t('productCenter.product.input')"
                :key="index"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          prop="id"
          :label="tableText['id']"
          min-width="100"
        />
        <el-table-column
          fixed="left"
          prop="loanProductName"
          :label="tableText['name']"
          min-width="150"
        />
        <el-table-column
          prop="loanProductType"
          :label="tableText['type']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['loanProductType'], 'type1') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="period"
          :label="tableText['periodsNumber']"
          min-width="100"
        />
        <el-table-column
          prop="loanQuotaMax"
          :label="tableText['amount']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['loanQuotaMix'] && scope.row['loanQuotaMax'] ? scope.row['loanQuotaMix'] + '-' + scope.row['loanQuotaMax'] : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="loanTermMax"
          :label="tableText['singlePeriod']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setLoanTerm(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="loanDayRate"
          :label="tableText['loanRate']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setLoanRate(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="gracePeriod"
          :label="tableText['gracePeriod']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['gracePeriod'] ? `${scope.row['gracePeriod']}(${$t('productCenter.product.type1')[0]['time']})` : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="gracePeriodDayRate"
          :label="tableText['gracePeriodDayRate']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['gracePeriodDayRate'] ? `${mulValue(scope.row['gracePeriodDayRate'], 100)} %` : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="overdueDayRate"
          :label="tableText['overdueDayRate']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['overdueDayRate'] ? `${mulValue(scope.row['overdueDayRate'], 100)} %` : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTimeStr"
          :label="tableText['creationTime']"
          min-width="170"
        />
        <el-table-column
          prop="createOperatorName"
          :label="tableText['founder']"
          min-width="100"
        />
        <el-table-column
          prop="modifyTimeStr"
          :label="tableText['updateTime']"
          min-width="170"
        />
        <el-table-column
          fixed="right"
          prop="status"
          :label="tableText['state']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['status'], 'state') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="editItem(scope.row)">{{ $t('common.operate.edit') }}</el-button>
            <el-button :loading="previewLoading" size="small" @click="preview(scope.row)">{{ tableText['preview'] }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <product-preview-dialog
      :preview-data="previewData"
      :show-dialog="isPreview"
      @change-dialog="changeDialog"
    />
    <settle-rule-dialog
      :show-dialog="isRules"
      :choose-item="chooseRuleItem"
      @change-dialog="changeDialog"
    />
    <product-dialog
      ref="productDialog"
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getProduct, loanProductPreview, realtime, settleRule } from '@/api/product'
import ProductPreviewDialog from '@/components/product/product-preview-dialog.vue'
import settleRuleDialog from '@/components/product/settle-rule-dialog.vue'
import ProductDialog from '@/components/product/product-dialog.vue'
import { mul } from '@/utils/method'
export default {
  name: 'Product',
  components: {
    ProductPreviewDialog,
    settleRuleDialog,
    ProductDialog
  },
  data() {
    return {
      loading: false,
      editDialog: false,
      tableData: [],
      inputData: null,
      selectData: 'id',
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      previewLoading: false,
      isPreview: false,
      previewData: {},
      realtimeLoading: false,
      settleRuleLoading: false,
      chooseRuleItem: {
        onceContainsServiceFee: null,
        oncePreTakeOffServiceFee: null,
        periodContainsServiceFee: null,
        periodPreTakeOffServiceFee: null
      },
      isRules: false,
      chooseItem: {
        id: null,
        loanProductName: null,
        loanProductType: 1,
        calculateType: null,
        loanQuotaMax: 0,
        loanQuotaMix: 0,
        loanQuotaIncrease: 1,
        loanTermMax: 0,
        loanTermMix: 0,
        loanTermIncrease: 1,
        loanDayRate: 0,
        annualInterestRate: 0,
        technologyRate: 0,
        auditRate: 0,
        gracePeriod: 0,
        gracePeriodDayRate: 0,
        overdueDayRate: 0,
        period: 1,
        status: 1,
        oughtPayRatio: []
      }
    }
  },
  mounted() {
    this.tableText = this.$t('productCenter.product.list')
    this.getData()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        id: null,
        loanProductName: null
      }
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.selectData = 'id'
      this.inputData = null
      this.getData()
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize
      }
      if (this.selectData && this.inputData) {
        data[this.selectData] = this.inputData
      }
      return data
    },
    getData() {
      this.loading = true
      getProduct(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    setValue(val, data) {
      const name = this.$t(`productCenter.product.${data}`).filter(item => {
        return item.value === val - 0
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    setLoanTerm(item) {
      let loanTerm = ''
      const loanTermMax = item['loanTermMax'] ? item['loanTermMax'] : 0
      const loanTermMix = item['loanTermMix'] ? item['loanTermMix'] : 0
      loanTerm = loanTermMix + '-' + loanTermMax
      const type = this.$t('productCenter.product.type1').filter(v => {
        return v.value === item['loanProductType']
      })
      const time = (type.length > 0 && type[0].time) ? type[0].time : ''
      loanTerm = loanTerm + '  ' + time
      return loanTerm
    },
    setLoanRate(item) {
      const loanRate = item['loanDayRate']
      const type = this.$t('productCenter.product.type1').filter(v => {
        return v.value === item['loanProductType']
      })
      const time = (type.length > 0 && type[0].interestRate) ? type[0].interestRate : ''
      return loanRate ? mul(loanRate, 100) + ` % (${time})` : ''
    },
    add() {
      this.choose({})
      this.editDialog = true
    },
    editItem(item) {
      this.choose(item)
      this.editDialog = true
    },
    preview(item) {
      loanProductPreview(item.id)
        .then(res => {
          this.previewLoading = false
          if (res.success) {
            this.previewData = res.data
            this.isPreview = true
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.previewLoading = false
          this.$message.error(err.message)
        })
    },
    changeDialog(data, state) {
      this[data] = state
    },
    realtimeUpdate() {
      this.realtimeLoading = true
      realtime()
        .then(res => {
          this.realtimeLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tips.operateSuccess'))
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.realtimeLoading = false
          this.$message.error(err.message)
        })
    },
    getRules() {
      settleRule()
        .then(res => {
          this.settleRuleLoading = false
          if (res.success) {
            this.chooseRule(res.data)
            this.isRules = true
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.settleRuleLoading = false
          this.$message.error(err.message)
        })
    },
    chooseRule(param) {
      this.chooseRuleItem.onceContainsServiceFee = param.onceContainsServiceFee
      this.chooseRuleItem.oncePreTakeOffServiceFee = param.oncePreTakeOffServiceFee
      this.chooseRuleItem.periodContainsServiceFee = param.periodContainsServiceFee
      this.chooseRuleItem.periodPreTakeOffServiceFee = param.periodPreTakeOffServiceFee
    },
    choose(param) {
      this.chooseItem.id = param.id
      this.chooseItem.loanProductName = param.loanProductName
      this.chooseItem.loanProductType = param.loanProductType || 1
      this.chooseItem.calculateType = param.calculateType
      this.chooseItem.loanQuotaMax = param.loanQuotaMax || 0
      this.chooseItem.loanQuotaMix = param.loanQuotaMix || 0
      this.chooseItem.loanQuotaIncrease = param.loanQuotaIncrease || 1
      this.chooseItem.loanTermMax = param.loanTermMax || 0
      this.chooseItem.loanTermMix = param.loanTermMix || 0
      this.chooseItem.loanTermIncrease = param.loanTermIncrease || 1
      this.chooseItem.loanDayRate = param.loanDayRate ? mul(param.loanDayRate, 100).toFixed(2) : 0
      this.chooseItem.annualInterestRate = param.annualInterestRate ? mul(param.annualInterestRate, 100).toFixed(2) : 0
      this.chooseItem.technologyRate = param.technologyRate ? mul(param.technologyRate, 100).toFixed(2) : 0
      this.chooseItem.auditRate = param.auditRate ? mul(param.auditRate, 100).toFixed(2) : 0
      this.chooseItem.gracePeriod = param.gracePeriod || 0
      this.chooseItem.gracePeriodDayRate = param.gracePeriodDayRate ? mul(param.gracePeriodDayRate, 100).toFixed(2) : 0
      this.chooseItem.overdueDayRate = param.overdueDayRate ? mul(param.overdueDayRate, 100).toFixed(2) : 0
      this.chooseItem.period = param.period || 1
      this.chooseItem.status = param.status
      const arr = []
      if (param.oughtPayRatio && param.oughtPayRatio.length > 0) {
        param.oughtPayRatio.forEach(v => {
          arr.push(mul(v, 100))
        })
      }
      this.chooseItem.oughtPayRatio = arr
      this.$refs.productDialog.changePeriod(param.period)
    },
    editSuccess() {
      this.getData()
    },
    mulValue(a, b) {
      return mul(a, b)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-divider{
  margin: 0 0 20px 0;
}
.el-card{
  margin: 10px;
}
.el-select{
  min-width: 120px;
}
.el-input{
  width: 400px;
}
</style>
